﻿using Assistant.Forms;
using WebAssistant.BusinessLogic;
using WebAssistant.BusinessLogic.Model;
using WebAssistant.WinUI;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using System.Text.Json;
using System.Text.Json.Serialization;
using Assistant.Tools;
using Assistant.Preview;

namespace Assistant
{
    public partial class FormMain : UIHeaderMainFooterFrame
    {
        List<Languages> languages = DataAccess.GetActivatedLanguages();

        public static FormMain mainPage;

        public FormMain()
        {
            InitializeComponent();
            InitializePage();
            InitializeNotifyIcon();
            this.lableVersion.Text = Shared.Version;
            this.Load += ConfigLoaded;
            //StartServer();
            mainPage = this;

            //OpenFormPreview();
        }

        #region 同步Odoo基础信息


        
        #endregion

        private void ConfigLoaded(object sender, EventArgs e) {
            bool auto_minimize = Convert.ToBoolean(DataAccess.GetSettingByKey("assistant.auto_minimize"));
            bool is_lock = Convert.ToBoolean(DataAccess.GetSettingByKey("assistant.lock_screen_status"));
            bool is_collapsed = Convert.ToBoolean(DataAccess.GetSettingByKey("assistant.interfaces_panel_collapsed"));
            string sytle = DataAccess.GetSettingByKey("assistant.style");
            if (auto_minimize)
            {
                NormalToMinimized();
            }            
            if (is_lock)
            {
                btnLock.PerformClick();
            }            
            if (is_collapsed)
            {
                tp_Interfaces.Collapsed = true;
            }
            if (sytle != "")
            {
                StyleManager.Style = (UIStyle)Enum.Parse(typeof(UIStyle), sytle);
            }

            //绑定接口服务
            BindInterfaceList();
        }

        #region 导航

        private void tsmlAPIDoc_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer", "http://localhost:" + Shared.Port);

        }

        private void tsmlAbout_Click(object sender, EventArgs e)
        {
            UIMessageBox.Show("Web助手 V1.0.0", "关于", Style, UIMessageBoxButtons.OK, false);
        }

        private void tsmiReport_Click(object sender, EventArgs e)
        {
            FormReportList report = new FormReportList();
            report.Show();
        }


        private void InitializePage()
        {
            //设置关联
            Header.TabControl = MainTabControl;

            //设置图标
            Header.SetNodeSymbol(Header.Nodes[0], 61461);
            Header.SetNodeSymbol(Header.Nodes[1], 61556);
            Header.SetNodeSymbol(Header.Nodes[2], 61613);
            Header.SetNodeSymbol(Header.Nodes[3], 61502);
            Header.SetNodeSymbol(Header.Nodes[4], 61867);
            foreach (Languages language in languages)
            {
                TreeNode childNode = new TreeNode();
                childNode.Name = language.Code;
                childNode.Text = language.Name;
                Header.Nodes[4].Nodes.Add(childNode);
            }

            Header.SetNodeSymbol(Header.Nodes[5], 61459);
            //绑定主题
            var styles = UIStyles.PopularStyles();
            foreach (UIStyle style in styles)
            {
                Header.CreateChildNode(Header.Nodes[3], style.DisplayText(), style.Value());
            }

            //增加页面到Main

            AddPage(new FormHome(), 1001);
            AddPage(new FormInterfaces(), 1002);
            AddPage(new FormSettings(), 1006);

            //设置Header节点索引
            Header.SetNodePageIndex(Header.Nodes[0], 1001);
            Header.SetNodePageIndex(Header.Nodes[1], 1002);
            Header.SetNodePageIndex(Header.Nodes[5], 1006);

            //显示默认界面
            Header.SelectedIndex = 0;
        }

        private void Header_NodeMouseClick(TreeNode node, int menuIndex, int pageIndex)
        {
            //if (menuIndex == 3)
            //{
            //    Point point = new Point(Header.RectangleToScreen(node.Bounds).X + Header.RectangleToScreen(node.Bounds).Width, Header.RectangleToScreen(node.Bounds).Height);
            //    Header.ShowContextMenuStrip(cmsTools, point);
            //}
            if (menuIndex == 4)
            {
                //ShowInfoDialog(node.Name);
            }
        }

        private void Header_MenuItemClick(string text, int menuIndex, int pageIndex)
        {
            switch (menuIndex)
            {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    FormTools formTools = new FormTools();
                    formTools.Show();
                    break;
                case 3:
                    UIStyle style = (UIStyle)pageIndex;
                    StyleManager.Style = style;
                    DataAccess.UpdateSettingByKey("assistant.style", style.ToString());
                    break;
                case 4:
                    break;
                case 5:
                    break;
            }
        }

        #endregion

        #region 窗体操作



        private void btnShowConsole_Click(object sender, EventArgs e)
        {
            FormConsole frm = new FormConsole();
            frm.Show();
        }

        private void btnLock_Click(object sender, EventArgs e)
        {
            FormLock frm = new FormLock();
            frm.ShowDialog();
            if (frm.IsUnlock)
            {
                UIMessageTip.ShowOk("解锁成功");
            }

            frm.Dispose();
        }

        

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            NormalToMinimized();
        }
        private void FormMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                NormalToMinimized();
            }
        }

        #endregion

        #region 通知图标

        private NotifyIcon notifyIcon; //定义通知图标

        // 当收到第二个进程的通知时，显示气球消息
        private void OnProgramStarted(object state, bool timeout)
        {
            this.notifyIcon.ShowBalloonTip(2000, "系统提示", "程序已在运行中，请勿重复打开...", ToolTipIcon.Info);
        }

        //初始化通知图标
        private void InitializeNotifyIcon()
        {
            this.notifyIcon = new NotifyIcon();
            this.notifyIcon.BalloonTipText = "Odoo Assistant 运行中... ...";
            this.notifyIcon.ShowBalloonTip(2000);
            this.notifyIcon.Text = "Odoo Assistant";           
            this.notifyIcon.Icon = (System.Drawing.Icon)Properties.Resources.ResourceManager.GetObject("IconLogo");
            this.notifyIcon.Visible = true;
            this.notifyIcon.ShowBalloonTip(5000);

            //托盘右键菜单项
            this.notifyIcon.ContextMenuStrip = new ContextMenuStrip();

            //隐藏菜单项
            this.notifyIcon.ContextMenuStrip.Items.Add("隐藏主窗口", null, (sender, eventArgs) => {
                NormalToMinimized();
            });

            //显示菜单项
            this.notifyIcon.ContextMenuStrip.Items.Add("显示主窗口", null, (sender, eventArgs) => {
                MinimizedToNormal();
            });

            //退出菜单项
            this.notifyIcon.ContextMenuStrip.Items.Add("退出", null, (sender, eventArgs) => {
                if (ShowAskDialog("确定退出吗？"))
                {

                    DateTime start = DateTime.Now;
                    DateTime end = DateTime.Now;
                    Logs Log = new Logs()
                    {
                        StartDate = start,
                        EndDate = end,
                        ServiceName = "Odoo Assistant",
                        MethodName = "Quit",
                    };

                    //写日志    
                    FormHome.homePage.AddListViewItem(Log);
                    WriteLog.Write(Log);
                    
                    //Application.Exit();//好像只在主线程可以起作用，而且当有线程，或是阻塞方法的情况下，很容易失灵。
                    //Application.ExitThread();//退出当前线程上的消息循环，并关闭该线程上的所有窗口， 也会失灵。
                    //Environment.Exit(0); // 这是最彻底的退出方式，不管什么线程都被强制退出，把程序结束的很干净。 
                    Process.GetCurrentProcess().Kill();//此方法完全奏效，绝对是完全退出。
                }
                else
                {
                    return;
                }
            });
        }

        //显示
        private void MinimizedToNormal()
        {
            this.Visible = true;
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
            //this.notifyIcon.Visible = false;
        }
        //隐藏
        private void NormalToMinimized()
        {
            this.ShowInTaskbar = false;
            this.Visible = false;
            //this.notifyIcon.Visible = true;
        }

        //关闭时最小化到托盘
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            NormalToMinimized();
        }

        //窗体状态改变时候触发，最小化到托盘
        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }

        }

        //双击打开程序
        private void OnNotifyIconDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            MinimizedToNormal();

            //if (e.Button == MouseButtons.Left)
            //{
            //    if (this.Visible == true)
            //    {
            //        this.Visible = false;
            //    }
            //    else
            //    {
            //        this.Visible = false;
            //        this.Activate();
            //    }
            //}
        }

        //隐藏操作
        private void hideMenuItem_Click(object sender, EventArgs e)
        {
            NormalToMinimized();
        }

        //显示操作
        private void showMenuItem_Click(object sender, EventArgs e)
        {
            MinimizedToNormal();
        }

        //帮助操作
        private void helpMenuItem_Click(object sender, EventArgs e)
        {

        }




        #endregion        

        #region 接口服务

        public void BindInterfaceList()
        {
            flpInterfaceList.Clear();
            List<Interfaces> InterfacesList = DataAccess.GetInterfaceList();
            foreach (var interfaces in InterfacesList)
            {
                UIInterFaceItem item = new UIInterFaceItem();
                item.Name = interfaces.Name;
                item.Summary = interfaces.Summary;
                item.InterFaceType = interfaces.Category;
                item.InterfaceKey = interfaces.Key;
                item.ShowRemoveButton = true;
                item.AutoStart = interfaces.AutoStart;
                if (interfaces.AutoStart)
                {
                    StartUPSServices(item); //启动通用打印服务
                }
                else
                {
                    StopUPSServices(item);  //停止通用打印服务
                }
     

                item.OnClickRemove += new UIInterFaceItem.OnClickRemoveHandle(RemoveInterface);
                item.OnClickChangeStated += new UIInterFaceItem.OnClickChangeStatedHandle(ChangeInterfaceState);
                item.OnSwitchState += new UIInterFaceItem.OnSwitchStateHandle(SwitchInterfaceState);
                flpInterfaceList.AddControl(item);
            }
        }

        private void tp_Interfaces_Resize(object sender, EventArgs e)
        {
            var interfaces_height = tp_Interfaces.Size.Height;
            var footer_info_height = up_Footer.Size.Height;
            
            Footer.Size = new Size(Footer.Size.Width, interfaces_height + footer_info_height) ;            
            DataAccess.UpdateSettingByKey("assistant.interfaces_panel_collapsed", (!tp_Interfaces.Collapsed).ToString());
        }

        private void ChangeInterfaceState(object sender, EventArgs e)
        {
            UISymbolButton btn = (UISymbolButton)sender;
            UIInterFaceItem item = (UIInterFaceItem)btn.Parent;
            //item.State = !item.State;
            if (item.State)
            {
                StartUPSServices(item);
            }
            else
            {
                StopUPSServices(item);
            }
        }

        private void SwitchInterfaceState(object sender, EventArgs e)
        {
            UISwitch uiswitch = (UISwitch)sender;
            UIInterFaceItem item = (UIInterFaceItem)uiswitch.Parent;

            //检查是否已经配置了接口
            if (CheckInterface(item))
            {
                var count = DataAccess.UpdateInterfaceAutoStartByKey(item.InterfaceKey, uiswitch.Active);
                if (count > 0)
                {
                    ShowSuccessTip(item.Name + "->设置为[" + (uiswitch.Active ? "自动启动" : "不自动启动") + "]成功！");
                }
                else
                {
                    ShowErrorTip(item.Name + "->设置为[" + (uiswitch.Active ? "自动启动" : "不自动启动") + "]失败！");
                }
            }
            else
            {
                ShowWarningDialog("当前接口尚未配置，请在 [设置 -> " + item.Name + "]，进行配置。");
                item.AutoStart = false;
            }
            
        }

        public void StartUPSServices(UIInterFaceItem item)
        {
            //检查是否已经配置了接口
            if (CheckInterface(item))
            {
                var count = DataAccess.UpdateInterfaceStateByKey(item.InterfaceKey, true);
                if (count > 0)
                {
                    //ShowSuccessNotifier(item.Name + "->[启动了服务]！");
                    string desc = item.Name + "->[启动了服务]！";
                    UINotifierHelper.ShowNotifier(desc, UINotifierType.OK, "成功", false, 3000);
                }
                else
                {
                    //ShowErrorNotifier(item.Name + "->[启动服务]失败！");
                    string desc = item.Name + "->[启动服务]失败！";
                    UINotifierHelper.ShowNotifier(desc, UINotifierType.ERROR, "失败", false, 3000);
                }
                item.State = true;
            }
            else
            {
                ShowWarningDialog("当前接口尚未配置，请在 [设置 -> " + item.Name + "]，进行配置。");
                item.State = false;
            }
        }

        public void StopUPSServices(UIInterFaceItem item)
        {
            var count = DataAccess.UpdateInterfaceStateByKey(item.InterfaceKey, false);
            if (count > 0)
            {
                //ShowSuccessNotifier(item.Name + "->[停止了服务]！");
                string desc = item.Name + "->[停止了服务]！";
                UINotifierHelper.ShowNotifier(desc, UINotifierType.OK, "成功", false, 3000);
            }
            else
            {
                //ShowErrorNotifier(item.Name + "->[停止服务]失败！");
                string desc = item.Name + "->[停止服务]失败！";
                UINotifierHelper.ShowNotifier(desc, UINotifierType.ERROR, "失败", false, 3000);
            }
            item.State = false;
        }

        private static bool CheckInterface(UIInterFaceItem item)
        {
            bool IsConfigured = false;
            if (item.InterFaceType == UIInterFaceItem.UIInterFaceType.Printer)
            {
                IsConfigured =  DataAccess.CheckPrinterExists(item.InterfaceKey);
            }

            return IsConfigured;
        }

        private void RemoveInterface(object sender, EventArgs e)
        {
            UISymbolButton btn = (UISymbolButton)sender;
            if (UIMessageDialog.ShowMessageDialog("确定删除吗？", "提示", true, UIStyle.Orange, true))
            {
                DateTime start = DateTime.Now;
                
                UIInterFaceItem item = (UIInterFaceItem)btn.Parent;
                //ShowInfoDialog(item.InterfaceKey);
                var result = DataAccess.UninstallInterfaceByKey(item.InterfaceKey);
                if (result > 0)
                {
                    ShowSuccessTip("卸载["+ item.Name + "]成功");
                    DateTime end = DateTime.Now;
                    Logs Log = new Logs()
                    {
                        StartDate = start,
                        EndDate = end,
                        ServiceName = item.Name,
                        MethodName = "Uninstall",
                    };

                    //写日志    
                    FormHome.homePage.AddListViewItem(Log);
                    WriteLog.Write(Log);

                    BindInterfaceList();

                    if (item.InterfaceKey == "interface.printer.universal_printing_service")
                    {
                        FormSettings.settingsPage.checkboxUPSInstallationStatus.Text = "未安装";
                        FormSettings.settingsPage.checkboxUPSInstallationStatus.Checked = false;
                        FormSettings.settingsPage.lableUPSList.Visible = false;
                        FormSettings.settingsPage.listboxUPSPrinters.Visible = false;
                        FormSettings.settingsPage.btnInstallUPS.Visible = true;

                        FormSettings.settingsPage.lableUPSOptions.Visible = false;
                        FormSettings.settingsPage.gbUPSOptions.Visible = false;
                        FormSettings.settingsPage.checkSilentPrinting.Visible = false;
                    }
                }
                else
                {
                    ShowErrorTip("卸载[" + item.Name + "]失败！");
                }
            }
            else
            {
                UIMessageTip.Show("你取消了操作!");
            }
        }





        #endregion

        
    }
}
